package com.extrace.ui.domain;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.extrace.loader.ExpressListLoader;
import com.extrace.loader.TransPackageLoader;
import com.extrace.misc.model.ExpressSheet;
import com.extrace.misc.model.TransNode;
import com.extrace.misc.model.TransPackage;
import com.extrace.misc.model.TransPackageContent;
import com.extrace.net.IDataAdapter;
import com.extrace.ui.main.ExTraceApplication;
import com.extrace.ui.main.R;
import com.extrace.ui.misc.TransNodeListActivity;
import com.zxing.util.CaptureActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class PackageEditActivity extends AppCompatActivity implements ActionBar.TabListener,IDataAdapter<TransPackage> {

    public static final int REQUEST_CAPTURE = 100;
    public static final int REQUEST_SOURCE = 101;
    public static final int REQUEST_TARGET = 102;
    public static final int REQUEST_EXPRESS = 103;
    public static final int REQUEST_EXPRESS_DESTROY = 104;


    SectionsPagerAdapter mSectionsPagerAdapter;

    ViewPager mViewPager;

    private List<TransPackageContent> mList;
    private TransPackage mItem;
    private TransPackageFragment baseFragment;

    private TransPackageLoader mLoader;
    private Intent mIntent;
    private ExpressListAdapter mAdapter;
    private List<ExpressSheet> ExList;

    private boolean new_tp = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_package_edit);

        mList = new ArrayList<TransPackageContent>();
        ExList = new ArrayList<ExpressSheet>();
        mAdapter = new ExpressListAdapter(ExList, this, "ExRCV");

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
                    }
                });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }

        mIntent = getIntent();

        if(mIntent.hasExtra("Action")) {
            if(mIntent.getStringExtra("Action").equals("New")) {
                if (((ExTraceApplication) getApplication()).getLoginUser().getName() == null) {
                    Toast.makeText(getApplicationContext(), "请登录！", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    new_tp = true;
                    StartCapture();
                }
            } else if(mIntent.getStringExtra("Action").equals("SORT")) {
                if (((ExTraceApplication) getApplication()).getLoginUser().getName() == null) {
                    Toast.makeText(getApplicationContext(), "请登录！", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    new_tp = false;
                    StartCapture();
                }
            }
            else{
                this.setResult(RESULT_CANCELED, mIntent);
                this.finish();
            }
        } else {
            this.setResult(RESULT_CANCELED, mIntent);
            this.finish();
        }
    }



    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        TransNode transNode;
        List<ExpressSheet> expressSheet;

        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case REQUEST_CAPTURE:
                        if(data.hasExtra("BarCode")) {
                            String id = data.getStringExtra("BarCode");
                            try {
                                mLoader = new TransPackageLoader(this,this);
                                if(new_tp) {
                                    new_tp = false;
                                    mLoader.New(id);
                                } else {
                                    mLoader.Load(id);
                                    SaveHistory(id,2);
                                }
                                baseFragment.RefreshExpressList(id);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    case REQUEST_SOURCE:
                        if (data.hasExtra("TransNode")) {
                            transNode = (TransNode) data.getSerializableExtra("TransNode");
                            mItem.setSourceNode(transNode);
                            baseFragment.disPlaySource(mItem);
                        }
                        break;
                    case REQUEST_TARGET:
                        if (data.hasExtra("TransNode")) {
                            transNode = (TransNode) data.getSerializableExtra("TransNode");
                            mItem.setTargetNode(transNode);
                            baseFragment.disPlayTarget(mItem);
                        }
                        break;
                    case REQUEST_EXPRESS:
                        if(data.hasExtra("ExpressSheet")) {
                            expressSheet = (List<ExpressSheet>) data.getSerializableExtra("ExpressSheet");
                            for(int i=0;i<expressSheet.size();i++) {
                                TransPackageContent tpc = new TransPackageContent();
                                tpc.setExpress(expressSheet.get(i));
                                tpc.setPkg(mItem);
                                tpc.setStatus(TransPackageContent.STATUS.STATUS_TRANSPORT);
                                mList.add(tpc);
                            }
                            baseFragment.disPlayExpressList(mList);
                        }
                        break;
                    case REQUEST_EXPRESS_DESTROY:
                        baseFragment.RefreshUI(mItem);
                        break;
                }
        }

    }

    private void StartCapture(){
        Intent intent = new Intent();
        intent.putExtra("Action","Captrue");
        intent.setClass(this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    private void GetExpressSheet(){
        Intent intent = new Intent();
        intent.putExtra("Action", "Packaging");
        intent.setClass(this, ExpressPackageListActivity.class);
        startActivityForResult(intent, REQUEST_EXPRESS);
    }

    private void GetTransNode(int intent_code) {
        Intent intent = new Intent();
        intent.setClass(this, TransNodeListActivity.class);
        if (intent_code == REQUEST_SOURCE) {
            if (baseFragment.mSourceNodeView.getTag() == null) {
                intent.putExtra("Action", "New");
            } else {
                intent.putExtra("Action", "New");
                intent.putExtra("TransNode", (TransNode) baseFragment.mSourceNodeView.getTag());
            }
        }
        else if(intent_code == REQUEST_TARGET){
            if(baseFragment.mTargetNodeView.getTag() == null){
                intent.putExtra("Action","New");
            }
            else{
                intent.putExtra("Action","New");
                intent.putExtra("TransNode",(TransNode)baseFragment.mTargetNodeView.getTag());
            }
        }
        startActivityForResult(intent, intent_code);
    }


    private void Save() {
        try {
            mLoader = new TransPackageLoader(this,this);
            if(mItem.getStatus() == TransPackage.STATUS.STATUS_CREATE)
                mItem.setStatus(TransPackage.STATUS.STATUS_PACKAGING);
            mLoader.Save(mItem);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (TransPackageContent tpc : mList) {
            try {
                mLoader = new TransPackageLoader(this, this);
                mLoader.SaveTPC(tpc);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        baseFragment.RefreshUI(mItem);
        baseFragment.disPlayExpressList(mList);
    }

    private void SaveHistory(String  id ,int method) {
        try {
            mLoader = new TransPackageLoader(this,this);
            mLoader.SaveHistory(id, method);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Finish(int method) {
        if(method == 1)
        {
            //mItem.setStatus(TransPackage.STATUS.STATUS_TRANSPORT);
            try {
                mLoader = new TransPackageLoader(this, this);
                mLoader.Save(mItem);
            } catch (Exception e) {
                e.printStackTrace();
            }
            SaveHistory(mItem.getID(),1);
        }
        else if (method == 2) {
            baseFragment.RefreshExpressList(mItem.getID());
            if (baseFragment.mList.size() == 0){
                mItem.setStatus(TransPackage.STATUS.STATUS_DESTROY);
                try {
                    mLoader = new TransPackageLoader(this, this);
                    mLoader.Save(mItem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        finish();
    }

    private void Destroy() {
        Intent intent = new Intent();
        intent.putExtra("Action", "ExPackaging");
        intent.putExtra("PackageID", mItem.getID());
        intent.setClass(this, ExpressPackageListActivity.class);
        startActivityForResult(intent, REQUEST_EXPRESS_DESTROY);
    }

    @Override
    public TransPackage getData() {
        return mItem;
    }

    @Override
    public void setData(TransPackage data) {
        mItem = data;
    }

    @Override
    public void notifyDataSetChanged() {
        if(baseFragment != null) {
            baseFragment.RefreshUI(mItem);
        }
        
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch(position){
                case 0:
                    baseFragment = TransPackageFragment.newInstance();
                    return baseFragment;
            }
            return ExpressEditActivity.ExpressEditFragment1.newInstance();
        }

        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_ex_edit1).toUpperCase(l);
            }
            return null;
        }
    }

    public static class TransPackageFragment extends Fragment {

        List<ExpressSheet> mList;
        private ExpressListLoader ExLoader;
        private int finishMethod = 1;

        private TextView mIDView;
        private ListView mTpListView;
        private TextView mSourceNodeView;
        private TextView mTargetNodeView;
        private TextView mTpStatusView;
        private TextView mCreateTimeView;

        private ImageView mCapture;
        private ImageView mPackaging;
        private ImageView mSourceNodeChoose;
        private ImageView mTargetNodeChoose;

        private Button mBtnUpdate;
        private Button mBtnFinish;
        private Button mBtnDestroy;

        ExpressListAdapter mAdapter;

        public static TransPackageFragment newInstance() {
            TransPackageFragment fragment = new TransPackageFragment();
            return fragment;
        }

        public TransPackageFragment() {}

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_transpackage_edit,
                    container, false);




            mIDView = (TextView) rootView.findViewById(R.id.transPackageId);
            mTpListView = (ListView) rootView.findViewById(R.id.expressSheetList);

            mList = new ArrayList<ExpressSheet>();
            mAdapter = new ExpressListAdapter(mList, this.getActivity(), "ExRCV");
            mTpListView.setAdapter(mAdapter);

            mSourceNodeView = (TextView) rootView.findViewById(R.id.packageSourceNode);
            mTargetNodeView = (TextView) rootView.findViewById(R.id.packageTargetNode);
            mTpStatusView = (TextView) rootView.findViewById(R.id.tpStatus);
            mCreateTimeView = (TextView) rootView.findViewById(R.id.tpCreateTime);

            mCapture = (ImageView) rootView.findViewById(R.id.action_tp_capture_icon);
            mCapture.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((PackageEditActivity) getActivity()).StartCapture();
                        }
                    });
            mPackaging = (ImageView) rootView.findViewById(R.id.action_packaging);
            mPackaging.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((PackageEditActivity) getActivity()).GetExpressSheet();
                        }
                    });

            mSourceNodeChoose = (ImageView) rootView.findViewById(R.id.action_SourceNode_Choose);
            mSourceNodeChoose.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((PackageEditActivity) getActivity()).GetTransNode(REQUEST_SOURCE);
                        }
                    }
            );

            mTargetNodeChoose = (ImageView) rootView.findViewById(R.id.action_TargetNode_Choose);
            mTargetNodeChoose.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((PackageEditActivity) getActivity()).GetTransNode(REQUEST_TARGET);
                        }
                    }
            );

            mBtnUpdate = (Button) rootView.findViewById(R.id.btnUpdate);
            mBtnUpdate.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((PackageEditActivity) getActivity()).Save();
                        }
                    }
            );

            mBtnFinish = (Button) rootView.findViewById(R.id.btnFinish);
            mBtnFinish.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((PackageEditActivity) getActivity()).Finish(finishMethod);
                        }
                    }
            );

            mBtnDestroy = (Button) rootView.findViewById(R.id.btnDestroy);
            mBtnDestroy.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((PackageEditActivity) getActivity()).Destroy();
                        }
                    }
            );


            return rootView;
        }

        void RefreshExpressList(String id) {
            try {
                ExLoader = new ExpressListLoader(mAdapter,((PackageEditActivity) getActivity()));
                ExLoader.LoadExpressListInPackage(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        void RefreshUI(TransPackage tp) {
            mIDView.setText(tp.getID());
            disPlaySource(tp);
            disPlayTarget(tp);

            String stText = "";
            switch (tp.getStatus()) {
                case TransPackage.STATUS.STATUS_CREATE:
                    stText = "正在创建";
                    break;
                case TransPackage.STATUS.STATUS_PACKAGING:
                    stText = "正在打包";
                    break;
                case TransPackage.STATUS.STATUS_TRANSPORT:
                    stText = "运输途中";
                    break;
                case TransPackage.STATUS.STATUS_SORT:
                    stText = "正在拆包";
                    break;
                case TransPackage.STATUS.STATUS_LANSHOU_PACKAGE:
                    stText = "揽收货篮";
                    break;
                case TransPackage.STATUS.STATUS_DELIVER_PACKAGE:
                    stText = "派送货篮";
                    break;
                case TransPackage.STATUS.STATUS_DESTROY:
                    stText = "已销毁";
                    break;
            }
            mTpStatusView.setText(stText);
            mCreateTimeView.setText(DateFormat.format("yyyy-MM-dd hh:mm:ss", tp.getCreateTime()));

            displayBtn(tp);
        }

        void disPlayExpressList(List<TransPackageContent> list) {
            for (int i=0;i<list.size();i++) {
                mList.remove(list.get(i).getExpress());
                mList.add(list.get(i).getExpress());
            }
            mAdapter.setData(mList);
            mAdapter.notifyDataSetChanged();
        }

        void disPlayExpressListByEx(List<ExpressSheet> list) {
            mList = list;
        }

        void disPlaySource(TransPackage tp) {
            if(tp.getSourceNode() != null)
                mSourceNodeView.setText(tp.getSourceNode().getNodeName());
            else mSourceNodeView.setText(null);
        }

        void disPlayTarget(TransPackage tp) {
            if(tp.getTargetNode() != null)
                mTargetNodeView.setText(tp.getTargetNode().getNodeName());
            else mTargetNodeView.setText(null);
        }

        void displayBtn(TransPackage tp) {
            if(tp.getStatus() == TransPackage.STATUS.STATUS_CREATE) {
                finishMethod = 1;
                mBtnUpdate.setVisibility(View.VISIBLE);
                mBtnDestroy.setVisibility(View.INVISIBLE);
                mBtnFinish.setVisibility(View.INVISIBLE);
            } else if(tp.getStatus() == TransPackage.STATUS.STATUS_PACKAGING) {
                finishMethod = 1;
                mBtnUpdate.setVisibility(View.VISIBLE);
                mBtnDestroy.setVisibility(View.INVISIBLE);
                mBtnFinish.setVisibility(View.VISIBLE);
            } else if(tp.getStatus() == TransPackage.STATUS.STATUS_TRANSPORT) {
                finishMethod = 2;
                mPackaging.setVisibility(View.INVISIBLE);
                mBtnUpdate.setVisibility(View.INVISIBLE);
                mBtnDestroy.setVisibility(View.VISIBLE);
                mBtnFinish.setVisibility(View.VISIBLE);
            } else if(tp.getStatus() == TransPackage.STATUS.STATUS_SORT) {
                finishMethod = 2;
                mPackaging.setVisibility(View.INVISIBLE);
                mBtnUpdate.setVisibility(View.VISIBLE);
                mBtnDestroy.setVisibility(View.VISIBLE);
                mBtnFinish.setVisibility(View.VISIBLE);
            } else if(tp.getStatus() == TransPackage.STATUS.STATUS_LANSHOU_PACKAGE) {
                finishMethod = 2;
                mPackaging.setVisibility(View.INVISIBLE);
                mBtnUpdate.setVisibility(View.INVISIBLE);
                mBtnDestroy.setVisibility(View.VISIBLE);
                mBtnFinish.setVisibility(View.INVISIBLE);
            } else if(tp.getStatus() == TransPackage.STATUS.STATUS_DELIVER_PACKAGE) {
                mBtnUpdate.setVisibility(View.INVISIBLE);
                mBtnDestroy.setVisibility(View.INVISIBLE);
                mBtnFinish.setVisibility(View.INVISIBLE);
            } else if (tp.getStatus() == TransPackage.STATUS.STATUS_DESTROY) {
                mBtnUpdate.setVisibility(View.INVISIBLE);
                mBtnDestroy.setVisibility(View.INVISIBLE);
                mBtnFinish.setVisibility(View.INVISIBLE);
            }
        }
    }
}
